﻿using LuShanTea.Admin.Web.App_Start;
using LuShanTea.Admin.Web.Models;
using LuShanTea.DTO;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.Controllers
{
    public class CategoryController : Controller
    {
        public ICategoryService CategoryService { get; set; }
        // GET: Category
        [CheckPermission("Category.List")]
        public ActionResult List()
        {
            var model = CategoryService.GetAll();
            return View(model);
        }
        [CheckPermission("Category.Delete")]
        [HttpPost]
        public ActionResult Delete(long id)
        {
            CategoryService.MakeDelete(id);
            return Json(new AjaxResult { Status = "ok" });
        }
        [CheckPermission("Category.Add")]
        [HttpGet]
        public ActionResult AddNew()
        {
            return View();
        }
        [CheckPermission("Category.Add")]
        [HttpPost]
        public ActionResult AddNew(CateGoryAddModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            var en = CategoryService.GetByName(model.Name);
            if (en != null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "该商品类别已存在" });
            }
            CategoryDTO dto = new CategoryDTO();
            dto.Name = model.Name;
            CategoryService.AddNew(dto);
            return Json(new AjaxResult { Status = "ok" });
        }
        [CheckPermission("Category.Edit")]
        [HttpGet]
        public ActionResult Edit(long id)
        {
            var model = CategoryService.GetById(id);
            if (model==null)
            {
                return Content("参数错误");
            }
            return View(model);
        }
        [CheckPermission("Category.Edit")]
        [HttpPost]
        public ActionResult Edit(CategoryEditModel model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = MVCHelper.GetValidMsg(ModelState) });
            }
            var en = CategoryService.GetByName(model.Name);
            if (en != null)
            {
                if (en.Id==model.Id)
                {
                    return Json(new AjaxResult { Status = "error", ErrorMsg = "该商品类别已存在" });
                }
            }
            CategoryService.Updata(model.Id,model.Name);
            return Json(new AjaxResult { Status = "ok" });
        }
    }
}